//
//  SSDKEncryptUtil.m
//  SuperSDK
//
//  Created by wyht－ios－dev on 15/10/7.
//  Copyright © 2015年 WYHT. All rights reserved.
//

#import "SSDKPluginEncryptUtil.h"
#import "SSDKPluginMD5.h"

@implementation SSDKPluginEncryptUtil

static NSString *SIGN=@"sign";

+ (NSString *)generateSignWithDictionary:(NSMutableDictionary *)dictionary
                              useSignKey:(NSString *)key {
    NSString *encStr = [self generateNormalizedStringWithDictionary:dictionary
                                                        withoutKey:SIGN];
    encStr = [[key stringByAppendingString:encStr]
              stringByAppendingString:key];
    return [SSDKPluginMD5 md5:encStr];
}

+ (NSString *)generateNormalizedStringWithDictionary:(NSMutableDictionary *)dictionary
                                          withoutKey:(NSString *)key {
    NSArray *keyArray = [dictionary allKeys];
    NSArray *sortedArray = [keyArray sortedArrayUsingSelector:@selector(compare:)];
    
    NSString *sb = [[NSString alloc] init];
    for (NSString* k in sortedArray) {
        if ([k isEqualToString:key]) {
            continue;
        }
        NSString *value = [dictionary valueForKey:k];
        if (!value) {
            value = @"";
        }
        
        value = [[value dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
        sb = [[[sb stringByAppendingString: k]
               stringByAppendingString: @"="]
              stringByAppendingString:value];
    }
    return sb;
    
}

+ (BOOL)checkSignWithDictionary:(NSMutableDictionary *)dictionary
                     useSignKey:(NSString *)key {
    NSString *sign = [dictionary valueForKey:SIGN];
    if (!sign) {
        return NO;
    }
    
    NSString *checkSign = [SSDKPluginEncryptUtil generateSignWithDictionary:dictionary
                                                           useSignKey:key];
    if ([checkSign isEqualToString:sign]) {
        return YES;
    }
    return NO;
}

@end
